
var moment = require('moment');

var connection = require('./connect');
var underscore = require('underscore');
var util = require('../util');
var async = require('async');


module.exports = {
  getIndexItem: function(req, res, next){
    connection.connect(function(err) {
      if (err) {
        console.error('error connecting: ' + err.stack);
        return;
      }

      console.log('connected as id ' + connection.threadId);
    });
    var query = "SELECT * FROM 'users'";
    connection.query(query, function(err, rows, fields) {
      if (err) throw console.log(err);
      res.send(rows);
    });
    var itemData =  {
      userData: {
        uid: "1001",
        userName: "7pure",
      },
      listItem: [
        {
          "id": 1001,
          "type": "article",
          "title": "「何以言物件謂『東西』而不謂『南北』，考究亦是眾說紛紜",
          "desc": "其實，大概是在那衹能賴以日光普照萬物的昔時，一天一天過日子的老百姓都明白了『白日依山盡』的每日風景，也就是祇有在那亮亮一輪日頭東昇西降之間的大白天裏，才是物件可以看得分明的時辰……」"
        },
        {
          "id": 1002,
          "type": "activity",
          "title": "狼人杀",
          "address": "江北区观音桥大融城",
          "time": "2017-10-31 12:30:00",
          "limitNum": "12",
          "remark": "请尽量早点到，过时不候",
          "save": "saved",
          "opinion": "upvote",
          "voteStatus": "selected",
          "joinPeoples":[
            {"uid": 10,
            "nickName": "7pure",
            "iconPath": "images/join-4.png"
            },
            {
              "uid": 11,
              "nickName": "kaid",
              "iconPath": "images/join-1.png"
            },
            {
              "uid": 12,
              "nickName": "zhan",
              "iconPath": "images/join-2.png"
            },
            {
              "uid": 12,
              "nickName": "grace",
              "iconPath": "images/join-3.png"
            }
          ]
        },
        {
          "id": 1003,
          "type": "foodEvaluate",
          "title": "法式香烤里脊",
          "time": "2017.11.10   13:00",
          "participateNum": "1024",
          "score": 4,
          "desc": "好久不见，烤个牛小排给你们吃，晚安！谢谢你选择了我，谢谢一起相伴这么多天，期待再相聚的一天"
        }
      ]
    };
    res.send(itemData);
  },
  getLeaderItem: function(req, res, next){
    var backgroundList = ["#b5bab9","#181d4b","#896a45","#5f5d46","#281f1d","#76becc","#f3715c","#8a8c8e","#94d6da","#afb4db"];
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var minTime = [year, month, day].map(util.formatNumber).join('-') + ' 00:00:00';
    var maxTime = [year, month, day+1].map(util.formatNumber).join('-') + ' 00:00:00';
    connection.query("SELECT * FROM users INNER JOIN leader_timeline ON leader_timeline.l_leaderid=users.u_id WHERE leader_timeline.l_time BETWEEN '"+minTime+"' AND '"+maxTime+"'", function(err, rows, fields) {
      if (err) {
        throw console.log(err)
      } else {
        if(rows != null && rows != "" && rows != [] ){
          var timelineArr = [],leaderArr = [];
          var tempid =  rows[0].u_id || "";
          var leader = new Object();
          var alreadyNum = 0;
          for (var i = 0; i < rows.length; i++) {
            if(rows[i].u_id == tempid){
            } else {
              leaderArr.push(leader);
              alreadyNum = 0;
              leader = new Object();
              timelineArr =[];
            }
            var timeLine = new Object();
            timeLine.l_matter =  rows[i].l_matter;
            var hour = rows[i].l_time.getHours(),half = "am";
            if( hour > 12) {half = "pm";}
            timeLine.l_time = util.formatNumber(hour)+ ":" + util.formatNumber(rows[i].l_time.getMinutes()) + " " + half;
            timeLine.l_address =  rows[i].l_address;
            timeLine.l_id =  rows[i].l_id;
            timeLine.l_desc =  rows[i].l_desc;
            if(rows[i].l_status == 2){alreadyNum = alreadyNum + 1};
            leader.alreadyNum = util.formatNumber(alreadyNum);
            timeLine.l_status =  rows[i].l_status;
            timelineArr.push(timeLine);
            var abc = timelineArr.sort(function(a,b){
              return parseFloat(a.l_time)-parseFloat(b.l_time)
            });
            leader.id = rows[i].u_id;
            leader.nickname = rows[i].u_nickname;
            leader.status = rows[i].u_status;
            leader.logo = rows[i].u_logo;
            leader.position = rows[i].u_position;
            leader.timeLine = abc;
            leader.timeLineNum = util.formatNumber(abc.length);
            leader.alreadyPer = (alreadyNum/abc.length)*100;
            var radomNum = Math.floor(Math.random()*10);
            leader.bgColor = backgroundList[0];
            tempid = rows[i].u_id;
          }
          if(leader != "" && leader != null) {
            leaderArr.push(leader);
          }
          res.send({status:200,data:leaderArr});
      } else {  res.send({status:201,message:"今日领导无日程数据！"});}
    }
    });
  },
  getLeader: function(req, res, next){
    var leaderKey = req.query.name,sql = '';
    if(leaderKey == "" || leaderKey == null || leaderKey == undefined){
      sql = "SELECT u_id,u_nickname,u_logo,u_status FROM users WHERE u_role='2'";
    } else {
      sql = "SELECT u_id,u_nickname,u_logo,u_status FROM users WHERE u_role='2' AND u_nickname LIKE '%" + leaderKey + "%'";
    };
    connection.query(sql, function(err, rows, fields) {
      if (err) {
        throw console.log(err);
        res.send({status:500,message:"服务器出错，请稍后尝试"});
      }else {
        res.send({status:200,data:rows});
      }
    });
    }
};
